package com.ncmmall.mall.controller.securitys;

import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.application.securitys.page.PageApplication;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.security.page.Page;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 权限资源页面管理
 *
 * @author tongchun
 */
@RequestMapping(value = "/securitys/page")
@Controller
@Slf4j
public class PageController {

    @Autowired
    private PageApplication pathApplication;

    @Autowired
    private OperationLogApplication logApplication;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 分页筛选
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, Page path) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = new HashMap<>();
        String hql = builderHQL(params, path);

        QueryPage<Page> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Page.class);
        model.addAttribute("page", page).addAttribute("params", path);
        return "securitys/page/list";
    }

    /**
     * 条件查询
     */
    private String builderHQL(Map<String, Object> params, Page page) {
        String hql = "select r from Page r where 1 = 1";
        if (StringUtils.isNotBlank(page.getName())) {
            hql += " and r.name like :name";
            params.put("name", "%" + page.getName() + "%");
        }
        return hql + " order by r.id desc ";
    }

    /**
     * 添加页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private String create(Model model) {

        model.addAttribute("page", new Page()).addAttribute("_method", "POST");

        return "securitys/page/form";
    }

    /**
     * 添加页面
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> create(HttpServletRequest request, Page page) {
        try {
            pathApplication.create(page);
            logApplication.eventOfSystem(Securitys.currentUser(), "添加系统页面" + page.getName(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[添加路径异常]", e);
            return ImmutableMap.of("status", false, "message", e.getMessage());
        }
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    private String edit(Model model, @PathVariable("id") long id) {
        Page path = queryChannelService.findOne("select r from Page r where r.id = :id", ImmutableMap.of("id", id), Page.class);
        model.addAttribute("page", path).addAttribute("_method", "PUT");

        return "securitys/page/form";
    }

    /**
     * 编辑页面
     */
    @RequestMapping(value = "/{id}/edit", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> edit(HttpServletRequest request, @ModelAttribute Page path) {
        try {
            pathApplication.modify(path);
            logApplication.eventOfSystem(Securitys.currentUser(), "编辑系统页面" + path.getName(), Securitys.getIp(request));
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[编辑页面异常]", e);
            return ImmutableMap.of("status", false, "message", e.getMessage());
        }
    }

    /**
     * 删除页面
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    private Map<String, Object> remove(HttpServletRequest request, long id) {
        try {
            if (!Webs.isAjaxRequest(request)) {
                throw new IllegalRequestException("request must be Ajax!");
            }
            Page page = queryChannelService.findOne("select r from Page r where r.id = :id", ImmutableMap.of("id", id), Page.class);
            logApplication.eventOfSystem(Securitys.currentUser(), "删除系统页面" + page.getName(), Securitys.getIp(request));
            pathApplication.remove(page);
            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            log.error("[路径删除异常]", e);
            return ImmutableMap.of("status", false, "message", e.getMessage());
        }
    }

}
